package net.wenku8.reader.view.file

import android.net.Uri
import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson2.JSON
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.entity.BookFile
import net.wenku8.reader.enums.FileBookInfo
import net.wenku8.reader.enums.FileBookText
import net.wenku8.reader.service.FileService
import net.wenku8.reader.util.formatTimeNum
import net.wenku8.reader.view.common.BaseViewModel
import java.util.Date

class FileBookcaseViewModel : BaseViewModel() {

    val bookList = mutableStateListOf<BookFile>()
    var delBookId : String = ""

    fun initData() {
        dataLoading.value = true
        viewModelScope.launch(Dispatchers.IO) {
            val list = FileService.readFolder(FileBookInfo)
            Log.i("initData:", list.toString())
            bookList.clear()
            list.reversed().forEach { json ->
                bookList.add(JSON.parseObject(json, BookFile::class.java))
            }
            dataLoading.value = false
        }
    }

    fun addBookFile(uri: Uri?){
        if (uri == null) return
        viewModelScope.launch(Dispatchers.IO) {
            val bookId = formatTimeNum(Date())
            FileService.copyFile(uri, FileBookText+bookId)
            val bookFile = BookFile()
            bookFile.bookId = bookId
            bookFile.title = FileService.getFileName(uri)?:""
            bookList.add(bookFile)
            FileService.writeFile(FileBookInfo+bookId, JSON.toJSONString(bookFile))
        }
    }

    fun delBookFile(){
        if (delBookId.isEmpty()) return
        bookList.removeIf { e -> e.bookId == delBookId }
        viewModelScope.launch(Dispatchers.IO) {
            FileService.deleteFile(FileBookInfo+delBookId)
        }
    }

}